<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | 属性数据控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\model\VersionModel;
use common\service\ReviewRoomService;
use common\service\ReviewTaskDelayService;
use common\service\ReviewTaskService;
use common\validate\ReviewTask;
use support\ErrorCode;
use think\Exception;
use think\Request;
use think\Response;
use Throwable;

class ReviewTaskController extends VerifyController
{
    /**
     * @var ReviewTaskService
     */
    protected $reviewTaskService;
    /** @var ReviewRoomService */
    protected $reviewRoomService;

    public function _initialize()
    {
        $this->reviewTaskService = ReviewTaskService::getInstance();
        $this->reviewRoomService = ReviewRoomService::getInstance();
    }


    /**
     * 审核任务 组装列表查询
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function waitAssembleList(Request $request)
    {
        $param = $request->param()['param'];
        $moduleCode = $request->param()['module_code'];
        $page = $param['page'] ?? [1, C("database.database_max_select_rows")];
        if ($moduleCode === 'shot') {
            $res = $this->reviewTaskService->waitAssembleStoryboardList($request->getTenantId(), $param['filter'], $page);
        } else {
            $res = $this->reviewTaskService->waitAssembleDesignList($request->getTenantId(), $param['filter'], $page);
        }
        return json(success_response('OK', $res));
    }

    /**
     * 组装播放列表
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function assemblePlayList(Request $request)
    {
        $param = $request->param()['data'];
        try {
            $res = $this->reviewTaskService->assemblePlayList($request->getTenantId(), $request->getUserId(), $param['name'], $param['entity_ids'], $param['module_code']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 已组装播放列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function assembledList(Request $request)
    {
        try {
            $param = $request->param()['param'];
            $page = $param['page'] ?? [1, C("database.database_max_select_rows")];
            if ($request->getModuleCode() === 'asset') {
                $res = $this->reviewTaskService->assembledAssetList($param['filter'], $page, $param['order']);
            } else {
                $res = $this->reviewTaskService->assembledShotList($param['filter'], $page, $param['order']);
            }
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 提交审核
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function submitReview(Request $request)
    {
        $data = $request->param()['data'];
        try {
            $res = $this->reviewTaskService->submitReview($request->getUserId(), $request->getTenantId(), $data);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 待审核播放列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function waitReviewPlayListVersion(Request $request)
    {
        $data = $request->param();
        $param = $data['param'];
        $page = $param['page'] ?? [1, C('default_page_total')];
        $moduleCode = $data['module_code'] ?? 'asset';
        try {
            $res = $this->reviewTaskService->waitReviewPlayListVersion($request->getUserId(), $param['filter'], $moduleCode, $page, $param['order']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询播放列表信息
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function selectPlayListTaskVersionInfo(Request $request)
    {
        $param = $request->param()['param'];
        $v = new ReviewTask();
        $v->scene('SelectPlayListTaskVersionInfoVersions');
        foreach ($param['task_versions'] as $version) {
            if (!$v->check($version)) {
                throw_strack_exception($v->getError(), ErrorCode::DATA_INVALID);
            }
        }
        $res = $this->reviewRoomService->selectPlayListTaskVersionInfo($param['task_versions']);
        return json(success_response('OK', $res));
    }

    /**
     * 检查任务关联的播放列表是否可以提交
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function checkTaskRelatedPlaylistCanSubmit(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->checkTaskRelatedPlaylistCanSubmit($param['id']);
        return json(success_response('OK', $res));
    }

    /**
     * 审核全部任务
     * @param Request $request
     * @return Response
     * @throws Exception
     * @throws Throwable
     */
    public function reviewAllByPlaylistVersion(Request $request)
    {
        throw_strack_exception("service Not available", ErrorCode::SERVICE_NOT_AVAILABLE);
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->reviewAllByPlaylistVersion($param['filter']['playlist_version_id'], $param['is_pass'] === 'yes', $request->getUserId());
        return json(success_response('OK', $res));
    }

    /**
     * 审核节点完成检查
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function reviewRequestNodeCheck(Request $request)
    {
        $param = $request->param()['param'];
		$version = model(VersionModel::class)->find($param['filter']['id']);
        $res = $this->reviewTaskService->checkReviewNeedHandleStatus($param['filter']['id'],$version);
        return json(success_response('OK', $res));
    }

    /**
     * 对比模式数据源
     * @param Request $request
     * @return Response
     */
    public function getCompareDataSource(Request $request)
    {
        $param = $request->param()['param'];
        try {
            $res = $this->reviewTaskService->getCompareDataSource($param['filter']['id']);
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 修复之前任务处理状态数据
     * @return Response
     * @throws Throwable
     */
    public function syncTaskDealStatus(Request $request)
    {
        try {
            $res = $this->reviewTaskService->syncTaskDealStatus();
            return json(success_response('OK', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }

    }

    /**
     * 获取提交审核任务
     * @return Response
     * @throws Throwable
     */
    public function getAssetSubmittedReviewTask(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->getAssetSubmittedReviewTask($param, $request->getTenantId(), $request->getUserId());
        return json(success_response('OK', $res));
    }

    /**
     * 获取审核列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskSubmitReview(Request $request)
    {
        $param = $request->param()['param'] ?? [];
        $res = $this->reviewTaskService->getTaskSubmitReview($param, $request->getTenantId(), $request->getUserId());
        return json(success_response('', $res));
    }

    /**
     * 获取资产已提交审核列表的子项
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getAssetSubmittedReviewPlaylistItem(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->getAssetSubmittedReviewPlaylistItem($param, $request->getTenantId(), $request->getUserId());
        return json(success_response('', $res));
    }

    /**
     * 修复当前进度角色
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function fixCurrentScheduleCodeInPlaylistVersion(Request $request)
    {
        $res = $this->reviewTaskService->fixCurrentScheduleCodeInPlaylistVersion();
        return json(success_response('', $res));
    }

    //=============异常管理

    /**
     * 延期任务
     * @param Request $request
     * @return Response
     * @throws Exception|\Exception
     */
    public function getDeferredTaskSelect(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->getDeferredTaskSelect($param, $request->getTenantId());
        return json(success_response('', $res));
    }

    /**
     * 未完成审核任务
     * @param Request $request
     * @return Response
     */
    public function getIncompleteReviewTask(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->reviewTaskService->getIncompleteReviewTask($param);
        return json(success_response('', $res));
    }

    /**
     * 获取任务审核进度
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskReviewSchedule(Request $request)
    {
        try {
            $param = $request->param()['data'];
            $res = $this->reviewTaskService->getTaskReviewSchedule($param, $request->getTenantId());
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 接受反馈
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function acceptFeedback(Request $request)
    {
        $param = $request->param()['param']['filter'];
        try {
            $res = $this->reviewTaskService->acceptFeedback($param);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询审核节点审核检查节点信息
     * @param Request $request
     * @return Response
     */
    public function queryReviewTaskVersionCheckList(Request $request)
    {
        $param = $request->param()['param'];
        $reviewRequestId = $param['review_request_id'];
        $reviewRequestNodeId = $param['review_request_node_id'];
        try {
            $res = $this->reviewTaskService->queryReviewTaskVersionCheckList($reviewRequestId, $reviewRequestNodeId, $request->getTenantId());
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }

    }

    /**
     * 获取审核节点及其子节点树
     * @param Request $request
     * @return Response
     */
    public function getVersionCheckListTree(Request $request)
    {
        $param = $request->param()['param'];

        try {
            $res = $this->reviewTaskService->getVersionCheckListTree($param, $request->getTenantId());
            return json(success_response('', $res));
        } catch (Exception $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 修复二次确认
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function fixReviewRequestNodeIsSecondConfirm(Request $request)
    {
        $res = $this->reviewTaskService->fixReviewRequestNodeIsSecondConfirm();
        return json(success_response('', $res));
    }

    /**
     * 修复任务的处理状态
     * @param Request $request
     * @return Response
     */
    public function fixTaskDealStatus(Request $request)
    {
        $res = $this->reviewTaskService->fixTaskDealStatus();
        return json(success_response('', $res));
    }

    /**
     * 更新老数据版本列表的进度
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function fixOldCurrentScheduleCodeInPlaylistVersion(Request $request)
    {
        $res = $this->reviewTaskService->fixOldCurrentScheduleCodeInPlaylistVersion();
        return json(success_response('', $res));
    }

    /**
     * 获取审核关联页面的统计
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function getTaskSubmitReviewStepCategoryCount(Request $request)
    {
        $param = $request->param();
        $filter = $param['param']['filter'];
        $res = $this->reviewTaskService->getTaskSubmitReviewStepCategoryCount($filter);
        return json(success_response('', $res));
    }

    /**
     * 修复审核列表子项的租户id
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function fixPlaylistItemVersionTenantId(Request $request)
    {
        $res = $this->reviewTaskService->fixPlaylistItemVersionTenantId();
        return json(success_response('', $res));
    }

    /**
     * 资产审核任务列表统计
     * @param Request $request
     * @return Response
     */
    public function reviewTaskListEntityCategoryCount(Request $request)
    {
        $param = $request->param()['param'];
        $filter = $param['filter'] ?? [];
        try {
            $res = $this->reviewTaskService->reviewTaskListEntityCategoryCount(
				$request->getTenantId(),
				$request->getUserId(),
				$filter
			);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 资产审核任务列表
     * @param Request $request
     * @return Response
     * @throws Exception
     */
	public function assetReviewTaskList(Request $request)
	{
		$param  = $request->param()['param'];

		try {
			$page   = $param['page'] ?? [1, C("database.database_max_select_rows")];
			$filter = $param['filter'] ?? [];
			$res = $this->reviewTaskService->assetReviewTaskList(
				$request->getTenantId(),
				$request->getUserId(),
				$param,
				$filter,
				$page,
			);
			return json(success_response('', $res));
		} catch (LogicException $e) {
			throw_strack_exception($e->getMessage(), $e->getCode());
		}
	}

    /**
     * 镜头审核任务列表
     * @param Request $request
     * @return Response
     */
    public function shotReviewTaskList(Request $request)
    {
        $param = $request->param()['param'];
        $page = $param['page'] ?? [1, C("database.database_max_select_rows")];
        $filter = $param['filter'] ?? [];
        try {
            $res = $this->reviewTaskService->shotReviewTaskList(
				$request->getTenantId(),
				$request->getUserId(),
				$param,
				$filter,
				$page
			);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 延期任务列表
     * @param Request $request
     * @return Response|void
     */
    public function delayList(Request $request)
    {
        $param = $request->param()['param'];
        $page = $param['page'] ?? [1, C("database.database_max_select_rows")];
        $filter = $param['filter'] ?? [];
        $extendFilter = $param['extend_filter'] ?? [];
        $initialEpisodeCodeList = $param['initial_episode_code_list'] ?? null;
        $departmentId = $param['department_id'] ?? null;
        $todoStepCategoryIds = $param['todo_step_category_ids'] ?? null;
        $todoEpisodeId = $param['todo_episode_id'] ?? null;
        try {
			$res = ReviewTaskDelayService::getInstance()->delayList(
				$request->getTenantId(),
				$filter,
				$extendFilter,
				$initialEpisodeCodeList,
				$departmentId,
				$todoStepCategoryIds,
				$todoEpisodeId,
				$page
			);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 延期任务-find
     * @param Request $request
     * @return Response|void
     */
    public function delayFind(Request $request)
    {
        $param = $request->param()['param'];
        $filter = $param['filter'] ?? [];
        try {
            $res = ReviewTaskDelayService::getInstance()->delayFind($filter);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 延期任务详情
     * @param Request $request
     * @return Response|void
     * @throws \Exception
     */
    public function delayItem(Request $request)
    {
        $param = $request->param()['param'];
        $filter = $param['filter'] ?? [];
        try {
            $res = ReviewTaskDelayService::getInstance()->delayItem($request->getTenantId(), $filter);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

	/**
	 * 计算审核中的任务数量(镜头加资产总和)
	 *
	 * @param \think\Request $request
	 *
	 * @return Response|void
	 * @throws \Exception
	 */
	public function reviewTaskListCount(Request $request)
	{
		try {
			$tenantId = $request->getTenantId();
			$userId = $request->getUserId();
			$result = $this->reviewTaskService->reviewTaskListCount($userId,$tenantId);
			return json(success_response('success', $result));
		}catch (LogicException $exception){
			throw_strack_exception($exception->getMessage(), $exception->getCode());
		}

	}
}
